<template>
  <van-button
    :icon="value ? 'star' : 'star-o'"
    :class="{
      collected: value, //value为true 类名生效 反则不生效
    }"
    @click="onCollect"
    :loading="loading"
  >
  </van-button>
</template>

<script>
import { addCollect, deleteCollect } from '@/api/article.js'
export default {
  name: 'CollectArticle',
  props: {
    value: {
      type: Boolean,
      required: true,
    },
    articleId: {
      type: [String,Number],
      required: true,
    },
  },
  data() {
    return {
      loading: false, //关注按钮的加载状态
    }
  },

  mounted() {},

  methods: {
    async onCollect() {
      this.loading = true
      try {
        if (this.value) {
          //已经收藏 取消收藏
          await deleteCollect(this.articleId)
        } else {
          //未收藏 添加收藏
          await addCollect(this.articleId)
        }
        //更新视图 及收藏状态 props中数据不能更改 需传到父组件
        this.$emit('input', !this.value)//更新视图 传到父组件数据才能改变
        this.$toast.success(!this.value?'收藏成功':'取消收藏')//这儿是马上使用这个数据 不是立即的
      } catch (err) {
        this.$toast('获取数据失败')
      }
      this.loading = false
    },
  },
}
</script>

<style lang="less" scoped>
.collected {
  .van-icon {
    color: yellow;
  }
}
</style>
